--Write a program that transposes the text in a file. For instance, it should convert
--"hello\nworld\n" to "hw\neo\nlr\nll\nod\n".


-- ghc --make xxx.hs

import System.Environment (getArgs)
import Data.Char

interactWith function inputFile outputFile = do
  input <- readFile inputFile
  writeFile outputFile (function input)

main = mainWith myFunction
  where mainWith function = do
          args <- getArgs
          case args of
            [input,output] -> interactWith function input output
            _ -> putStrLn "error: exactly two arguments needed"
        -- replace "id" with the name of our function below
        myFunction = fixLines

-------------------------------------------------------------

fixLines :: String -> String
fixLines input = unlines (transposeLines (splitLines input))


-- 相当于lines，但可以混合各种行分隔符
splitLines :: String -> [String]
splitLines [] = []
splitLines cs =
  let (pre, suf) = break isLineTerminator cs
  in pre : case suf of
    ('\r':'\n':rest) -> splitLines rest
    ('\r':rest) -> splitLines rest
    ('\n':rest) -> splitLines rest
    _ -> []
isLineTerminator c = c == '\r' || c == '\n'


transposeLines :: [String] -> [String]
transposeLines [] = []
transposeLines (line1:line2:lines) = zipWith concatTwoChar line1 line2

concatTwoChar a b = a : [b]
  
